#include "toolbar.h"
#include <QFile>
#include "../widgets/icon.h"
#include <QMetaObject>
#include <QDebug>
#include "../aurasim.h"

ToolBar::ToolBar(QWidget *parent) : QToolBar(parent)
{
    initUI();
    initConnections();
}

void ToolBar::initUI()
{
    setAllowedAreas(Qt::TopToolBarArea);
    setMinimumHeight(40);
    setContentsMargins(0, 0, 0, 0);

    QStringPairList actionPairs;
    actionPairs << QStringPair(":/svgs/solid/play.svg", tr("start"))
                << QStringPair(":/svgs/solid/undo-alt.svg", tr("undo"))
                << QStringPair(":/svgs/solid/redo-alt.svg", tr("redo"))
                << QStringPair(":/svgs/solid/code.svg", tr("code"));
    mActionMethod << QStringPair(tr("start"), "actionStartToggle")
                  << QStringPair(tr("undo"), "actionUndo")
                  << QStringPair(tr("redo"), "actionRedo")
                  << QStringPair(tr("code"), "actionRedo");

    foreach (const QStringPair& actionPair, actionPairs) {
        QAction* action = addAction(Icon(actionPair.first, QColor(100, 200, 133)), actionPair.second);
        mActionMap.insert(actionPair.second, action);
    }

//    addAction(Icon(":/svgs/solid/caret-right.svg", QColor(100, 200, 133)), tr("start"));
//    addAction(Icon(":/svgs/solid/undo-alt.svg", QColor(100, 200, 133)), tr("undo"));
//    addAction(Icon(":/svgs/solid/redo-alt.svg", QColor(100, 200, 133)), tr("redo"));

    QFile qssFile(":/qss/toolbar-default.qss");
    if(qssFile.open(QIODevice::ReadOnly)) {
        QString qss = qssFile.readAll();
        this->setStyleSheet(qss);
        qssFile.close();
    }
}

void ToolBar::initConnections()
{
    connect(this, &QToolBar::actionTriggered, [=](QAction* action){
        foreach (const QStringPair& actionPair, mActionMethod) {
            if(actionPair.first == action->text()) {
                if(this->metaObject()->indexOfMethod(QString("%1%2").arg(actionPair.second).arg("()").toStdString().data()) != -1) {
                    QMetaObject::invokeMethod(this, actionPair.second.toStdString().data());
                }
            }
        }
    });

    connect(Aurasim::app(), &Aurasim::AurasimApp::simStateChanged, [=](const Aurasim::SimState& state){
        QAction* action = mActionMap.value(tr("start"));
        if(state == Aurasim::Start) {
            action->setIcon(Icon(":/svgs/solid/stop.svg", QColor(100, 200, 133)));
        } else{
            action->setIcon(Icon(":/svgs/solid/play.svg", QColor(100, 200, 133)));
        }
    });
}

void ToolBar::actionStartToggle()
{
//    mActionMap.value(tr("start"))->setIcon(Icon(":/svgs/solid/pause.svg", QColor(100, 200, 133)));
    if(Aurasim::app()->simState == Aurasim::Stop)
        Aurasim::startSim();
    else
        Aurasim::stopSim();
}

void ToolBar::actionRedo()
{

}

void ToolBar::actionUndo()
{

}

void ToolBar::actionCode()
{

}
